package com.ibeeking.found.content.b.rest.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaMediaService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ObjectUtil;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.content.b.rest.service.IWxMediaFileService;
import com.ibeeking.found.content.b.rest.service.IWxOpenService;

import com.ibeeking.found.content.service.common.constants.enums.WxMediaTypeEnum;

import com.ibeeking.nematos.exception.BusinessException;

import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * 微信素材文件
 *
 * @Author ibeeking
 */
@Service
public class WxMediaFileServiceImpl implements IWxMediaFileService {

    @Resource
    private IWxOpenService wxOpenServiceImpl;


    @Override
    public String uploadMedia(InputStream inputStream, String fileType) throws WxErrorException {
        if (StringUtils.isBlank(fileType)) {
            throw new BusinessException("上传素材失败 未获取到原始文件类型");
        }
        Long tenantId = UserUtils.getTenantID();
        WxMaService wxMaService = wxOpenServiceImpl.getWxOpenMaService(tenantId);
        WxMaMediaService mediaService = wxMaService.getMediaService();
        String type = WxMediaTypeEnum.IMAGE.getType();
        WxMediaUploadResult wxMediaUploadResult = mediaService.uploadMedia(type, fileType, inputStream);
        if (ObjectUtil.isNotNull(wxMediaUploadResult)) {
            return wxMediaUploadResult.getMediaId();
        } else {
            throw new BusinessException("上传素材失败 异常返回:" + JSON.toJSONString(wxMediaUploadResult));
        }
    }
}
